package top.tresman.cxxcommon.config;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;
import java.util.List;

@ConfigurationProperties(prefix = "cors")
@Data
@Configuration
public class CorsConfig {
    private String allowedOrigins;
    private String allowedMethods;
    private String allowedHeaders;
    private String exposedHeaders;
    private Boolean allowCredentials;
    private Long maxAge;

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        if (StringUtils.isNotBlank(allowedOrigins)) {
            List<String> originList = Arrays.stream(allowedOrigins.split(",")).map(String::trim).toList();
            for (String origin : originList) {
                config.addAllowedOriginPattern(origin);
            }
        }
        config.setAllowCredentials(allowCredentials);    // 允许携带凭证
        config.addAllowedMethod(allowedMethods);        // 允许任何方法（POST、GET等）
        config.addAllowedHeader(allowedHeaders);
        config.setMaxAge(maxAge);             // 在3600秒内，不需要再发送预检请求

        if (StringUtils.isNotBlank(exposedHeaders)) {
            List<String> exposeHeaderList = Arrays.stream(exposedHeaders.split(",")).toList();
            config.setExposedHeaders(exposeHeaderList);// 需要暴露给前端的响应头，在使用jwt时会用到
        }

        // 添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        // 返回新的CORS过滤器
        return new CorsFilter(source);
    }
}
